﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bigger.Base.Cache;
using Bigger.Web.Mvc;
using Bigger.Framework;
using Bigger.Web.Helper;

namespace CJAtech.BBS.Web.Filters
{
    public class BBSQrCodeAuthorFilter : BiggerActionFilter
    {
        /// <summary>
        /// 是否二维码授权校验
        /// </summary>
        public bool IsQrCodeAuth { get; set; }
        public BBSQrCodeAuthorFilter(bool isQrCodeAuth)
        {
            this.IsQrCodeAuth = isQrCodeAuth;
        }
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            string bbsName = filterContext.RouteData.Values["BBSName"].ToString();
            if (bbsName.IsNull())
            {
                filterContext.Result = new Http404Result();
                return;
            }

            if (this.IsQrCodeAuth)
            {
                string qrToken = bbsName + CookieHelper.GetCookieValue(bbsName + "QrToken");
                //假设用缓存DB
                var CurrentCache = Bigger.Core.Cache.CacheHelper.CacheInstance;
                if (CurrentCache.GetCache(qrToken) == null)
                {
                    if (SystemWebAsset.IsAjaxRequest())
                    {
                        filterContext.Result = new JsonResult
                        {
                            Data = new InvokeResult { ResultCode = "QrTokenExpired", ResultMessage = "对不起，授权登录已失效" },
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        };
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("/bbs/" + bbsName + "/authredirection");
                    }
                }
            }
        }
    }
}